package com.lfc.myframe.ui

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.gyf.immersionbar.ImmersionBar
import com.lfc.myframe.R
import com.lfc.myframe.TestA
import com.lfc.myframe.base.BaseA
import com.lfc.myframe.databinding.ActivityMainBinding
import com.lfc.myframe.ui.Fg01.HomeFG
import com.lfc.myframe.ui.Fg02.SecondFG
import com.lfc.myframe.ui.Fg03.ThirdFG
import com.lfc.myframe.ui.Fg04.MineFG
import com.lfc.myframe.utils.RadioButtonUtils
import com.tamsiree.rxkit.TLog
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel


class MainActivity : BaseA<ActivityMainBinding>(), CoroutineScope by MainScope() {
    companion object {
        fun EnterThis(context: Context, string: String = "", int: Int = 0) {
            var intent = Intent(context, MainActivity().javaClass)
            intent.putExtra("strInfo", string)
            intent.putExtra("Type", int)
            context.startActivity(intent)
        }
    }

    override fun useEventBus(): Boolean {
        return true
    }

    private val BOTTOM_INDEX: String = "bottom_index"

    private var mHomeFG: HomeFG? = null
    private var mSecondFG: SecondFG? = null
    private var mThirdFG: ThirdFG? = null
    private var mMineFG: MineFG? = null

    private var mFragments = arrayOfNulls<Fragment>(4)
    private var mPreFragmentFlag = 0

    override fun ReGetData() {
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        initView()
        initData()
        getData()
    }

    private fun initView() {
        SetToolBarVisiabale(false)
        initImmersionBar()
//        showFragment(mIndex)
        initFragment()
        selectFragment()
    }

    private fun initData() {
//        TestA.EnterThis(baseContext)

    }


    private fun getData() {
    }

    protected fun initImmersionBar() {
        //在BaseActivity里初始化
        mImmersionBar = ImmersionBar.with(this)
        mImmersionBar?.statusBarDarkFont(true, 0.2f)?.init()

        //在BaseActivity里初始化
        //        ImmersionBar.with(this).navigationBarColor(R.color.colorPrimary).init();
    }


    fun initFragment() {
        mFragments[0] = HomeFG()
        mFragments[1] = SecondFG()
        mFragments[2] = ThirdFG()
        mFragments[3] = MineFG()
        initLoadFragment(R.id.container, 0, mFragments)
    }

    // 参数一 是一个FrameLayout的ID，用来动态加载Fragment，
    fun initLoadFragment(
        containerId: Int,
        showFragment: Int,
        fragments: Array<Fragment?>
    ) {
        //获取到FragmentManager实例的同时去开启事物
        val transaction =
            supportFragmentManager.beginTransaction()
        for (i in 0 until fragments.size) {
            //首先将Fragment添加到事务中
            transaction?.add(containerId, fragments[i]!!, fragments[i]!!.tag)
            //默认展示 fragments[showFragment]
            //这里做首次Fragment的展示，如果不是指定的Fragment就先隐藏，需要的时候再显示出来
            if (i != showFragment) transaction.hide(fragments[i]!!)
        }
        //提交事物
        transaction.commitAllowingStateLoss()
    }

    open fun selectFragment() {
        //注册监听事件
        mBottomNav?.setItemIconTintList(null)
        mBottomNav?.setOnNavigationItemSelectedListener(
            BottomNavigationView.OnNavigationItemSelectedListener { menuItem: MenuItem ->
                when (menuItem.itemId) {
                    R.id.home -> {
                        showAndHideFragment(
                            mFragments[0]!!,
                            mFragments[mPreFragmentFlag]!!
                        )
                        mPreFragmentFlag = 0
                    }
                    R.id.wechat -> {
                        showAndHideFragment(
                            mFragments[1]!!,
                            mFragments[mPreFragmentFlag]!!
                        )
                        mPreFragmentFlag = 1
                    }
                    R.id.project -> {
                        showAndHideFragment(
                            mFragments[2]!!,
                            mFragments[mPreFragmentFlag]!!
                        )
                        mPreFragmentFlag = 2
                    }
                    R.id.system -> {
                        mFragments[mPreFragmentFlag]?.let {
                            showAndHideFragment(
                                mFragments[3]!!,
                                it
                            )
                        }
                        mPreFragmentFlag = 3
                    }
                    R.id.setting -> {
                        mFragments[4]?.let {
                            mFragments[mPreFragmentFlag]?.let { it1 ->
                                showAndHideFragment(
                                    it,
                                    it1
                                )
                            }
                        }
                        mPreFragmentFlag = 4
                    }
                }
                true
            }
        )
    }

    //加载不同的Fragment
    open fun showAndHideFragment(
        show: Fragment,
        hide: Fragment
    ) {
        val transaction =
            supportFragmentManager.beginTransaction()
        if (show !== hide) transaction.show(show).hide(hide).commitAllowingStateLoss()
    }

    private var mExitTime: Long = 0
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (System.currentTimeMillis().minus(mExitTime) <= 2000) {
                finish()
            } else {
                mExitTime = System.currentTimeMillis()
                showToast(getString(R.string.exit_tip))
            }
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onDestroy() {
        super.onDestroy()
        mHomeFG = null
        mSecondFG = null
        mThirdFG = null
        mMineFG = null
        cancel()
    }

    override val bindingInflater: (LayoutInflater) -> ActivityMainBinding
        get() = ActivityMainBinding::inflate

}
